package com.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.library.common.base.ApiResult;
import com.library.common.entity.MyPage;
import com.library.common.utils.PageUtil;
import com.library.entity.BookDataTypeEntity;
import com.library.entity.BookTypeEntity;
import com.library.entity.ResourceEntity;
import com.library.service.*;
import lombok.extern.slf4j.Slf4j;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class appInterfaceServiceImpl implements appInterfaceService {

    @Autowired
    private RecommendManageService recommendManageService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private BookDataTypeService dataTypeService;
    @Autowired
    private BookTypeService bookTypeService;
    private Map<String,String> map;
    public ApiResult getProductResources() {
        List<Map> list = new ArrayList<>();

        LambdaQueryWrapper<ResourceEntity> recommendManageWrapperwrapper = Wrappers.lambdaQuery();
        recommendManageWrapperwrapper.ne(ResourceEntity::getCover, "http://61.163.243.7:9999/digitallibrary/file/lengleng/暂无封面.jpg");
        recommendManageWrapperwrapper.orderByDesc(ResourceEntity::getPageView);
        recommendManageWrapperwrapper.isNotNull(ResourceEntity::getBriefIntroduction);
        recommendManageWrapperwrapper.last("LIMIT 6");
        List<ResourceEntity> list2 = resourceService.list(recommendManageWrapperwrapper);
        Map map1 = new HashMap();
        map1.put("dataTypeId", null);
        map1.put("dataType", "热门推荐");
        map1.put("resource", list2);
        list.add(map1);

        LambdaQueryWrapper<BookDataTypeEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BookDataTypeEntity::getDataTypeStatus, "1");
        for (BookDataTypeEntity bookDataTypeEntity : dataTypeService.list(wrapper)) {
            Map map = new HashMap();
            map.put("dataTypeId", bookDataTypeEntity.getId());
            map.put("dataType", bookDataTypeEntity.getDataType());
            LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
            Wrapper.eq(ResourceEntity::getDataTypeId, bookDataTypeEntity.getId());
            Wrapper.isNotNull(ResourceEntity::getBriefIntroduction);
            Wrapper.orderByDesc(ResourceEntity::getPageView);
            Wrapper.last("LIMIT 6");
            List<ResourceEntity> list1 = resourceService.list(Wrapper);
            map.put("resource", list1);
            list.add(map);
        }
        return ApiResult.ok(list);
    }

    @Override
    public ApiResult getTypeResources(Long id) {
        List<Map> list = new ArrayList<>();
        LambdaQueryWrapper<BookTypeEntity> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(BookTypeEntity::getDataTypeStatus, "0");
        wrapper.eq(BookTypeEntity::getDatatypeId, id);
        for (BookTypeEntity type : bookTypeService.list(wrapper)) {
            Map map = new HashMap();
            map.put("dataTypeId", type.getId());
            map.put("name", type.getBookType());
            LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
            Wrapper.eq(ResourceEntity::getBookTypeId, type.getId());
            Wrapper.orderBy(true, true, ResourceEntity::getPageView);
            Wrapper.last("LIMIT 6");
            List<ResourceEntity> list1 = resourceService.list(Wrapper);
            map.put("resource", list1);
            list.add(map);
        }
        return ApiResult.ok(list);
    }

    @Override
    public ApiResult getResources(Long id, Page page) {
        if(page.getCurrent()==0)
        {
            page.setCurrent(1);
        }
        page.setSize(9);
        LambdaQueryWrapper<ResourceEntity> Wrapper = Wrappers.lambdaQuery();
        Wrapper.eq(ResourceEntity::getBookTypeId, id);
        Wrapper.orderByDesc(ResourceEntity::getType);
        Wrapper.orderByDesc(ResourceEntity::getPageView);
        PageHelper.startPage((int)page.getCurrent(), 9);
        List<ResourceEntity> list = resourceService.list(Wrapper);
        PageInfo<ResourceEntity> info = new PageInfo<>(list);
        MyPage<ResourceEntity> resourceEntityMyPage = PageUtil.PageInfo2MyPage(info);
        //Wrapper.orderBy(true, true, ResourceEntity::getPageView);
        return ApiResult.ok(resourceEntityMyPage);
    }

    @Override
    public ResponseEntity<String> downloadAndParseEpub(String epubUrl) {
       //String s = "http://10.100.24.103:9000/lengleng/" + epubUrl;
        epubUrl = "http://10.100.24.103:9000"+epubUrl.replace("https://zhongtai.zhongjiaoyuntu.com:9002","");
        try {
            URL url = new URL(epubUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream;

            if (connection.getResponseCode() >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }

            try (BufferedInputStream in = new BufferedInputStream(inputStream)) {
                // 解析EPUB文件
                Book book = (new EpubReader()).readEpub(in);

                // 获取HTML内容
                StringBuilder htmlContent = new StringBuilder();
                int i = 1;
                for (nl.siegmann.epublib.domain.Resource resource : book.getContents()) {
                    String content = new String(resource.getData());
                    content = saveImages(content, i);
                    htmlContent.append(content);
                    i++;
                }

                return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_HTML)
                        .body(htmlContent.toString());
            }
        } catch (IOException e) {
            log.info("epub异常:{}",e);
            e.printStackTrace();
            return ResponseEntity.badRequest().body("处理EPUB文件时发生错误。");
        }
    }

    public ResponseEntity<String> downloadAndParseEpub1(String epubUrl) {
        // 1. URL处理改用更安全的URI组件
        final String targetBase = "http://10.100.24.103:9000";
        final String sourceBase = "https://zhongtai.zhongjiaoyuntu.com:9002";

        if (!epubUrl.startsWith(sourceBase)) {
            return ResponseEntity.badRequest().body("Invalid EPUB URL format");
        }
        String processedUrl = targetBase + epubUrl.substring(sourceBase.length());

        HttpURLConnection connection = null;
        try {
            // 2. 使用URLConnection更规范的打开方式
            URL url = new URI(processedUrl).toURL();
            connection = (HttpURLConnection) url.openConnection();

            // 3. 添加超时设置（单位：毫秒）
            connection.setConnectTimeout(30_000);
            connection.setReadTimeout(60_000);

            // 4. 显式设置请求方法
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode < HttpStatus.OK.value() || responseCode >= HttpStatus.BAD_REQUEST.value()) {
                log.error("EPUB download failed. Response code: {}, URL: {}", responseCode, processedUrl);
                return ResponseEntity.status(responseCode).body("Failed to download EPUB");
            }

            try (InputStream inputStream = connection.getInputStream();
                 BufferedInputStream bufferedStream = new BufferedInputStream(inputStream)) {

                // 5. 使用try-with-resources确保资源关闭
                Book book = new EpubReader().readEpub(bufferedStream);

                // 6. 改进内容处理方式
                StringBuilder htmlContent = new StringBuilder();
                int chapterCounter = 1;

                for (Resource resource : book.getContents()) {
                    String content = processResource(resource, chapterCounter++);
                    htmlContent.append(content);
                }

                return ResponseEntity.ok()
                        .contentType(MediaType.TEXT_HTML)
                        .body(htmlContent.toString());
            }
        } catch (URISyntaxException e) {
            log.error("Invalid URL format: {}", processedUrl, e);
            return ResponseEntity.badRequest().body("Invalid URL format");
        } catch (IOException e) {
            log.error("IO error processing EPUB from: {}", processedUrl, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error processing EPUB file");
        } catch (Exception e) {
            log.error("Unexpected error processing EPUB", e);
            return ResponseEntity.status(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED).body("Unexpected error");
        } finally {
            // 7. 确保断开连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    // 8. 提取资源处理方法
    private String processResource(Resource resource, int chapterNumber) throws IOException {
        String content = new String(resource.getData(), StandardCharsets.UTF_8);
        return saveImages(content, chapterNumber);
    }



    private String saveImages(String content, int chapterNumber) {
        int i = 0;
        while (content.contains("data:image/png;base64,")) {
            int startIndex = content.indexOf("data:image/png;base64,");
            int endIndex = content.indexOf("\"", startIndex);
            String base64Data = content.substring(startIndex + 22, endIndex);

            // Save image to file
            String fileName = "chapter_" + chapterNumber + "_image_" + i + ".png";
            saveImageToFile(base64Data, fileName);

            // Replace Base64 data with file path
            content = content.replace("data:image/png;base64," + base64Data, fileName);
            i++;
        }

        return content;
    }

    private void saveImageToFile(String base64Data, String fileName) {
        try {
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            try (FileOutputStream imageOutputStream = new FileOutputStream(fileName)) {
                imageOutputStream.write(imageBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String unicode(String url) {
        try {
            String s = "http://61.163.243.7:9999/digitallibrary/bookExposure/lengleng/Book/";
            String[] segments = url.split("/");
            int length = segments.length;
            if (length >= 2) {
                String segment = segments[length - 2];
                String segment1 = segments[length - 1];
                System.out.println(segments[length - 2] + "/" + segments[length - 1]);
                String encodedStr = URLEncoder.encode(segment, StandardCharsets.UTF_8.toString());
                String encodedStr1 = URLEncoder.encode(segment1, StandardCharsets.UTF_8.toString());
                s = s + encodedStr + "/" + encodedStr1;
            }

            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
